package com.example.revise.ui.gallery

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.revise.R
import com.example.revise.VideoPlayerActivity
import com.example.revise.data.VideoItem

class GalleryAdapter(private val items: List<GalleryItem>) : 
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val TYPE_HEADER = 0
        private const val TYPE_VIDEO = 1
    }

    class HeaderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val titleText: TextView = view as TextView
    }

    class VideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val thumbnailView: ImageView = view.findViewById(R.id.thumbnailView)
        val titleText: TextView = view.findViewById(R.id.videoTitle)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_HEADER -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_gallery_header, parent, false)
                HeaderViewHolder(view)
            }
            else -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_gallery_video, parent, false)
                VideoViewHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (val item = items[position]) {
            is GalleryItem.Header -> {
                (holder as HeaderViewHolder).titleText.text = item.title
            }
            is GalleryItem.Video -> {
                val videoHolder = holder as VideoViewHolder
                videoHolder.thumbnailView.setImageResource(item.video.videoResId)
                videoHolder.titleText.text = item.video.title
                
                // Add click listener to play video in full screen
                videoHolder.itemView.setOnClickListener {
                    val intent = VideoPlayerActivity.createIntent(
                        it.context,
                        item.video.videoResId,
                        item.video.title,
                        item.video.description
                    )
                    it.context.startActivity(intent)
                }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return when (items[position]) {
            is GalleryItem.Header -> TYPE_HEADER
            is GalleryItem.Video -> TYPE_VIDEO
        }
    }

    override fun getItemCount() = items.size
}

sealed class GalleryItem {
    data class Header(val title: String) : GalleryItem()
    data class Video(val video: VideoItem) : GalleryItem()
} 